// pages/registerPrese/index.js
const api = require('../../config/api');
const util = require('../../utils/util.js')
const apiSupplier = require('../../config/supplier.js');
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 富文本编辑器
    formats: {},
    readOnly: false,
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,


    showCalendar: false,
    showLevel: false,
    currentDate: new Date().getTime(),
    minDate: new Date(1900, 0, 1).getTime(),
    maxDate: new Date().setFullYear(new Date().getFullYear() + 10),
    activeName: '',
    fileList: [],
    supplierAll: [],
    qualification_levels: [],
    performance_evaluations: [],
    form: {
      id: null,
      classifyId: null,
      classifyName: null,
      orderNumber: null,
      name: null,
      fullName: null,
      legalPerson: null,
      landlineNumber: null,
      registeredCapital: 1,
      establishDate: util.formatDate(new Date()),
      companyWebsite: null,
      contacts: null,
      phone: null,
      address: null,
      qualificationLevel: null,
      qualificationLevelName: '',
      qualifyLevel:'',
      achievement: null,
      quality: '0',
      speed: '0',
      securitys: '0',
      businessAffairs: '0',
      awardWinning: '0',
      creditScore: null,
      recordNumber: null,
      remarks: null,
      companyImage: null,
      businessLicense:null,
      authorizationBook:null,
      verifyState:0,
      createUser:null
    }
  },
  onCollapseChange(event) {
    this.setData({
      activeName: event.detail,
    });
  },
  deleteFile(event) {
    let column = event.currentTarget.dataset.type
    this.data.form[column] = null

    this.setData({
      form: {
        ...this.data.form

      }
    })
  },
  afterRead(event) {
    const {
      file
    } = event.detail;
    let column = event.currentTarget.dataset.type
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    let _this = this
    wx.uploadFile({
      url: api.uploadUrl, // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'file',
      formData: {},
      success(res) {
        // 上传完成需要更新 fileList
        if (res.data) {
          _this.data.form[column] = res.data
          _this.setData({
            form: {
              ..._this.data.form
            }
          });
        }
      },
    });
  },

  onChange(event) {

    let column = event.currentTarget.dataset.type
    this.data.form[column] = event.detail
    this.setData({
      form: {
        ...this.data.form
      }
    })
  },
  // 富文本编辑器
  bindtextarea(e) {
    this.data.form.achievement = e.detail.html,
    this.setData({
      form: this.data.form,
    })
  },

  onConfirm(event) {

    let column = event.currentTarget.dataset.type
    let data = event.detail

    if (column == 'establishDate') {
      this.data.form[column] = util.formatDate(new Date(data))
    } else if (column == 'qualificationLevel') {
      if (data && data.value) {
        this.data.form.qualificationLevelName = data.value.dictLabel
        this.data.form.qualificationLevel = data.value.dictValue
      }
    }
    this.setData({
      form: {
        ...this.data.form
      }
    })
    this.onClose()
  },

  getSupplierAll() {
    wx.request({
      url: apiSupplier.leftList,
      data: {},
      method: 'GET',
      success: (res) => {
        if (res.data.code === 100) {
          let obj = res.data.object || []
          let datas = []
          obj.forEach(x => {
            datas.push({
              text: x.classifyName,
              value: x.id
            })
          })
          this.setData({
            supplierAll: datas
          })
        }
      }
    });
  },
  onShowHander(event) {
    let column = event.currentTarget.dataset.type
    this.setData({
      [column]: true
    })
  },
  onClose() {
    this.setData({
      showCalendar: false,
      showLevel: false,
    })
  },
  submit(){
    if(!this.data.form.name){
      return Notify({ type: 'warning', message: '请输入企业简称' })
    }
    if(!this.data.form.classifyId){
      return Notify({ type: 'warning', message: '请选择企业分类' })
    }
    if(!this.data.form.fullName){
      return Notify({ type: 'warning', message: '请输入企业名称' })
    }

    if(!this.data.form.legalPerson){
      return Notify({ type: 'warning', message: '请输入法人' })
    }
    if(!this.data.form.registeredCapital){
      return Notify({ type: 'warning', message: '请输入注册资本' })
    }
    if(!this.data.form.establishDate){
      return Notify({ type: 'warning', message: '请选择成立日期' })
    }
    if(!this.data.form.contacts){
      return Notify({ type: 'warning', message: '请输入联系人' })
    }

    if(!this.data.form.phone){
      return Notify({ type: 'warning', message: '请输入联系方式' })
    }
    // if(!this.data.form.recordNumber){
    //   return Notify({ type: 'warning', message: '请输入备案号' })
    // }
    if(!this.data.form.address){
      return Notify({ type: 'warning', message: '请输入企业地址' })
    }
    const userid = wx.getStorageSync('wxUser') ? wx.getStorageSync('wxUser').id : ''
    this.data.form.createUser = userid
    wx.showLoading({title: '正在提交...'})
    wx.request({
      url: api.regiestPreseUrl,
      data:  this.data.form,
      method: 'POST',
      success: (res) => {
        wx.hideLoading();
        if(res && res.data &&  res.data.code == 200){
          wx.navigateBack({})
        }
      },
      fail: (res) => {
        wx.hideLoading();
      }
    });
  },
  getDictDataList() {
    wx.request({
      url: api.dictDataListUrl,
      data: {
        type: 'information_category'
      },
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          let data = res.data.data
          this.setData({
            informationCategorys: data
          })
        }
      }
    });
  },

  getqualification_level() {
    wx.request({
      url: api.dictDataListUrl,
      data: {
        type: 'qualification_level'
      },
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          let data = res.data.data
          this.setData({
            qualification_levels: data
          })
        }
      }
    });
  },
  getperformance_evaluation() {
    wx.request({
      url: api.dictDataListUrl,
      data: {
        type: 'performance_evaluation'
      },
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          let data = res.data.data
          this.setData({
            performance_evaluations: data
          })
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getSupplierAll()
    this.getqualification_level()
    this.getperformance_evaluation()


        // 富文本编辑器
    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({
      isIOS
    })
    this.updatePosition(0)
    const that = this
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)
    })   

  },
// 富文本编辑器
readOnlyChange() {
  this.setData({
    readOnly: !this.data.readOnly
  })
},
onEditorReady() {
  const that = this
  wx.createSelectorQuery().select('#editor').context(function (res) {
    that.editorCtx = res.context
    //请求完数据后再调用这个方法，才能取到数据写入编辑器')
    that.editorCtx.setContents({
      html: that.data.form.achievement //将数据写入编辑器内
    })
  }).exec()
},
updatePosition(keyboardHeight) {
  const toolbarHeight = 50
  const {
    windowHeight,
    platform
  } = wx.getSystemInfoSync()
  let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight - (132 + 'rpx')
  this.setData({
    editorHeight,
    keyboardHeight
  })
},
calNavigationBarAndStatusBar() {
  const systemInfo = wx.getSystemInfoSync()
  const {
    statusBarHeight,
    platform
  } = systemInfo
  const isIOS = platform === 'ios'
  const navigationBarHeight = isIOS ? 44 : 48
  return statusBarHeight + navigationBarHeight
},
blur() {
  this.editorCtx.blur()
},
format(e) {
  let {
    name,
    value
  } = e.target.dataset
  if (!name) return
  this.editorCtx.format(name, value)

},
onStatusChange(e) {
  const formats = e.detail
  this.setData({
    formats
  })
},
insertDivider() {
  this.editorCtx.insertDivider({
    success: function () {
    }
  })
},
clear() {
  this.editorCtx.clear({
    success: function (res) {
    }
  })
},
removeFormat() {
  this.editorCtx.removeFormat()
},
insertDate() {
  const date = new Date()
  const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
  this.editorCtx.insertText({
    text: formatDate
  })
},
insertImage() {
  const that = this
  wx.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    success: function (res) {
      const tempFilePaths = res.tempFilePaths
      wx.uploadFile({
        url: api.uploadUrl,
        filePath: tempFilePaths[0],
        name: 'file',
        formData: {
          'user': 'test'
        },
        success(res) {
          const data = res.data
          that.editorCtx.insertImage({
            src: data,
            width: '80%',
            success: function () {
            }
          })
        }
      })
    }
  })
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})